package com.xyb.service;

import com.xyb.dao.ChapterMapper;
import com.xyb.dao.ChapterRepository;
import com.xyb.entity.Chapter;
import com.xyb.utils.IdUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterService {
    @Resource
    private IdUtils idUtils;
    @Resource
    private ChapterRepository chapterDao;
    @Resource
    private ChapterMapper chapterMapper;

    public List<Chapter> selectChapterListByCourseId(Long courseId) {
        List<Chapter> list = chapterDao.findByCourseIdAndStatusOrderByShowOrder(courseId, 1);
        return list;
    }

    public List<Chapter> selectChapterListAndCourseDetailsByCourseId(Long courseId) {
        List<Chapter> list = chapterMapper.selectChapterListAndCourseDetailsByCourseId(courseId);
        return list;
    }

    public String insertChapterByCourseId(Chapter chapter) {
        long nextId = idUtils.nextId();
        chapter.setChapterId(nextId);
        chapter.setStatus(1);
        Integer showOrder = chapterDao.countByCourseId(chapter.getCourseId());
        chapter.setShowOrder(showOrder == null ? 0 : showOrder++);
        chapterDao.save(chapter);
        return "success";
    }

    public String updateChapterByChapterId(Chapter chapter) {
        chapterDao.save(chapter);
        return "success";
    }

    public String deleteChapterByChapterId(Long chapterId) {
        chapterDao.deleteById(chapterId);
        return "success";
    }

    public String updateChapterShowOrder(Long[] chapterIds) {
        List<Chapter> list = new ArrayList<>();
        for (int i = 0, length = chapterIds.length; i < length; i++) {
            Chapter chapter = new Chapter();
            chapter.setChapterId(chapterIds[i]);
            chapter.setShowOrder(i);
            list.add(chapter);
        }
        chapterDao.saveAll(list);
        return "success";
    }
}
